import BaseController from './base';

export default class ShopController extends BaseController {
  public async create() {
    const { ctx, service } = this;
    try {
      const { name } = ctx.request.body;
      if (!name) this.fail(400, '请输入店铺名！');
      const data = await service.shop.create({ name });
      if (data.err) return this.fail(data.status, data.err);
      this.success(data);
    } catch (error) {
      ctx.throw(JSON.stringify(error), 400);
    }
  }

  public async update() {
    const { ctx, service } = this;
    try {
      const { shopId } = ctx.params;
      const options = ctx.request.body;
      if (Object.keys(options).length === 0) return this.fail(400, '请输入有效的参数！');
      const data = await service.shop.update(shopId, options);
      if (data.err) return this.fail(data.status, data.err);
      this.success(data);
    } catch (error) {
      ctx.throw(JSON.stringify(error), 400);
    }
  }

  public async getShopById() {
    const { ctx, service } = this;
    try {
      const { shopId } = ctx.params;
      const data = await service.shop.getShopById(shopId);
      if (data.err) return this.fail(data.status, data.err);
      this.success(data);
    } catch (error) {
      ctx.throw(JSON.stringify(error), 400);
    }
  }

  public async removeShop() {
    const { ctx, service } = this;
    try {
      const { shopId } = ctx.params;
      const data = await service.shop.removeShop(shopId);
      if (data.err) return this.fail(data.status, data.err);
      this.success(data);
    } catch (error) {
      ctx.throw(JSON.stringify(error), 400);
    }
  }
}
